package com.zmh.license.info;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author summer
 * @date 2023-03-13 11:07
 */
@Slf4j
public class LinuxServer extends LicenseAbstractServer {

    @Override
    protected List<String> getIpAddress() {
        List<InetAddress> localAllInetAddress = getLocalAllInetAddress();
        return localAllInetAddress.stream().map(InetAddress::getHostAddress).distinct().map(String::toLowerCase).collect(Collectors.toList());

    }

    @Override
    protected List<String> getMacAddress() {
        List<InetAddress> localAllInetAddress = getLocalAllInetAddress();
        return localAllInetAddress.stream().map(this::getMacByInetAddress).distinct().collect(Collectors.toList());
    }

    @Override
    protected String getCpuInfo() throws IOException {
        String[] shell = {"/bin/bash","-c","dmidecode -t processor | grep 'ID' | awk -F ':' '{print $2}' | head -n 1"};
        return common(shell);
    }

    private String common(String[] shell) throws IOException {
        String serialNumber = "";
        Process process = Runtime.getRuntime().exec(shell);
        process.getOutputStream().close();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line = reader.readLine().trim();
        if(StrUtil.isNotEmpty(line)){
            serialNumber = line;
        }

        reader.close();
        return serialNumber;
    }

    @Override
    protected String getMainBoardSerial() throws IOException {
        String[] shell = {"/bin/bash","-c","dmidecode | grep 'Serial Number' | awk -F ':' '{print $2}' | head -n 1"};
        return common(shell);
    }
}
